<template>
    <page-wrapper>
        <div class="scheme_header_box flex-column">
            <div class="flex-row filter_item">
                <table-search @search="search(1)" @reset="reset()">
                    <template slot="form">
                        <form-item label="">
                            <a-input v-model="form.name" style="width:120px;" placeholder="请输入姓名" />
                        </form-item>
                        <form-item label="">
                            <a-tree-select
                                v-model="form.deptId"
                                allowClear
                                style="width:240px"
                                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                                :tree-data="deptList"
                                :replaceFields="{
                                    children: 'children',
                                    title: 'deptName',
                                    key: 'deptId',
                                    value: 'deptId'
                                }"
                                placeholder="请选择项目部"
                            >
                            </a-tree-select>
                        </form-item>
                        <form-item label="">
                            <a-select v-model="form.status" style="width:120px;" allowClear placeholder="请选择状态">
                                <a-select-option :value="item.value" v-for="item in jobStatus" :key="item.value">{{
                                    item.label
                                }}</a-select-option>
                            </a-select>
                        </form-item>
                        <form-item label="">
                            <a-select v-model="form.level" style="width:120px;" allowClear placeholder="请选择评级">
                                <a-select-option :value="item.value" v-for="item in jobLevels" :key="item.value">{{
                                    item.label
                                }}</a-select-option>
                            </a-select>
                        </form-item>
                    </template>
                    <template slot="control">
                        <a-button class="form_btn search_item btn_space" type="primary" icon="download" @click="downloadWorker"
                            >导出数据</a-button
                        >
                        <a-button class="form_btn search_item btn_space btn_reset" icon="upload"
                            >导入数据 <input class="upload_file" type="file" accept=".xlsx, .xls" @change="uploadFile"
                        /></a-button>
                    </template>
                    <template slot="extra">
                        <a-button
                            class="filter-item"
                            type="primary"
                            :disabled="hasPerm(['staff:labor:add'])"
                            icon="plus"
                            @click="showInfo()"
                            >新建员工</a-button
                        >
                        <a-button
                            class="form_btn btn_space btn_primary"
                            type="dashed"
                            icon="download"
                            @click="downloadTemplate"
                            >下载模版</a-button
                        >
                    </template>
                </table-search>
            </div>
        </div>
        <div class="table_scroll">
            <table-list
                :loading="loading"
                :columns="columns"
                rowKey="id"
                :pagination="pagination"
                :data="list"
                :scroll="{ x: 1500 }"
            >
                <template slot="imageUrl" slot-scope="{ text }">
                    <a-avatar @click="showPreview(text)" shape="square" :size="64" :src="text" />
                </template>
                <template slot="age" slot-scope="{ text }">
                    <span v-if="text.age">{{ text.age }}岁</span>
                </template>
                <template slot="deptId" slot-scope="{ text }">
                    <field-tag :value="text" type="deptId" showType="deptName" :data="expandDeptData"></field-tag>
                </template>
                <template slot="workType" slot-scope="{ text }">
                    <field-tag :data="workTypes" :value="text.workType" type="value" showType="label"></field-tag>
                </template>
                <template slot="level" slot-scope="{ text }">
                    <list-status :data="jobLevels" :value="text.level" :dot="false"></list-status>
                </template>
                <template slot="idNumber" slot-scope="{ text }">
                    {{ dealIdCard(text.idNumber) }}
                </template>
                <template slot="sex" slot-scope="{ text }">
                    {{ text == 'M' ? '男' : '女' }}
                </template>
                <template slot="insureStatus" slot-scope="{ text }">
                    {{ text == 1 ? '是' : '否' }}
                </template>
                <template slot="status" slot-scope="{ text }">
                    <a-switch
                        checked-children="在职"
                        un-checked-children="离职"
                        :disabled="hasPerm(['staff:labor:update'])"
                        :key="text.id"
                        :default-checked="text.status == 'A' ? true : false"
                        @change="onSwitchStatus(text)"
                    />
                </template>

                <template slot="action" slot-scope="{ text }">
                    <a-button
                        size="small"
                        type="primary"
                        :disabled="hasPerm(['staff:labor:update'])"
                        @click="showInfo(text)"
                        >编辑</a-button
                    >
                    <a-button
                        size="small"
                        class="btn_space"
                        :disabled="text.status == 'A' || hasPerm(['staff:labor:remove'])"
                        type="danger"
                        @click="remove(text)"
                        >删除</a-button
                    >
                    <a-button
                        size="small"
                        class="btn_space btn_reset"
                        :disabled="hasPerm(['staff:labor:resume'])"
                        @click="showResume(text)"
                        >履历</a-button
                    >
                </template>
            </table-list>
        </div>

        <template v-if="isShowInfo">
            <labour-info :info="itemInfo" :deptList="deptList" @cancel="isShowInfo = false" @submit="search(1)" />
        </template>
        <a-modal v-model="isPreview" :footer="null" style="width:400px;" title="查看人脸">
            <img style="width:100%" :src="previewUrl" />
        </a-modal>

        <template v-if="isShowResume">
            <resume-info :form="itemInfo" @cancel="isShowResume = false" />
        </template>
    </page-wrapper>
</template>
<script>
import table from '@/mixins/table';
import { columns } from './columns';
import LabourInfo from './components/info';
import deptApi from '@/api/system/dept';
import { idCard } from '@/utils';
import { getCache } from '@/utils/session';
import {
    remoteList,
    deleteInfo,
    updateInfo,
    remoteDownloadFileTemplate,
    remoteDownloadWorkerFile,
    remoteImportWorkers
} from '@/api/staff/labour';
import { workTypes, jobStatus, jobLevels } from '@/views/staff/dictionary';
import ResumeInfo from './components/resume.vue';
import { downloadFile } from '@/utils';

export default {
    name: 'Labour',
    mixins: [table],
    components: {
        LabourInfo,
        ResumeInfo
    },
    data() {
        let originForm = {
            name: '',
            deptId: undefined,
            status: undefined,
            level: undefined
        };
        return {
            workTypes,
            jobStatus,
            jobLevels,
            columns,
            originForm,
            form: {
                ...originForm
            },
            deptList: [],
            expandDeptData: [],
            itemInfo: null,
            isShowInfo: false,
            isPreview: false,
            previewUrl: '',
            isShowResume: false
        };
    },
    async created() {
        await this.getResource();
        this.search(1);
    },
    methods: {
        async search(page) {
            try {
                this.isShowInfo = false;
                this.loading = true;
                if (page) {
                    this.form.page = page;
                }
                this.list = [];
                let res = await remoteList(this.form);
                let { list, total } = res.data;
                this.list = list;
                this.total = total;
                this.selectionBox = [];
            } finally {
                this.loading = false;
            }
        },
        showResume(item) {
            this.isShowResume = true;
            this.itemInfo = item;
        },
        //新增 编辑信息
        showInfo(item = {}) {
            this.isShowInfo = true;
            this.itemInfo = item;
        },
        //删除信息
        remove(item) {
            this.$confirm({
                title: '提示',
                content: '确定要删除人员信息？',
                okText: '确定',
                cancelText: '取消',
                onOk: async () => {
                    try {
                        let ids = [];
                        if (item) {
                            ids = [item.id];
                        } else {
                            let selectionBox = this.selectionBox;
                            selectionBox.map(async item => {
                                ids.push(item.id);
                            });
                        }
                        await deleteInfo({ ids });
                        this.$message.success('删除成功!');
                        this.search(1);
                    } catch (err) {}
                },
                onCancel() {}
            });
        },
        showPreview(text) {
            this.isPreview = true;
            this.previewUrl = text;
        },
        //是否开启
        async onSwitchStatus(item) {
            console.log(item);
            try {
                let { status } = item;
                item.status = status == 'A' ? 'I' : 'A';
                this.loading = true;
                await updateInfo(item);
                this.$message.success('操作成功!');
            } catch (err) {
                let { status } = item;
                item.status = status == 'A' ? 'I' : 'A';
            } finally {
                this.loading = false;
            }
        },
        //获取资源列表信息
        async getResource() {
            let userInfo = getCache('userInfo') || { userId: '' };
            let { userId } = userInfo;
            let deptResult = await deptApi.remoteList({ userId });
            this.deptList = deptResult.data;
            this.expandDeptData = [];
            this.expandData(deptResult.data);
        },
        //多层次数据展开
        expandData(data) {
            if (Array.isArray(data)) {
                data.map(item => {
                    this.expandDeptData.push(item);
                    if (item.children && item.children.length) {
                        this.expandData(item.children);
                    }
                });
            }
        },
        dealIdCard(number) {
            return idCard(number);
        },
        //导入数据
        async uploadFile(e) {
            let files = e.target.files;
            const hide = this.$message.loading('处理导入劳务人员数据');
            try {
                this.loading = true;
                const formData = new FormData();
                formData.append('file', files[0]);
                let res = await remoteImportWorkers(formData);
                let {code,msg} = res;
                if(code==200){
                    this.$message.success('导入成功');
                    this.search(1)
                }else{
                    this.$message.error(msg)
                }
            } catch (err) {
                //解决多次上传同一文件 没动作的问题
                e.target.value = '';
            } finally {
                e.target.value = '';
                this.loading = false;
                setTimeout(hide, 100);
            }
        },
        //导出数据
        async downloadWorker() {
            this.loading = true;
            const hide = this.$message.loading('导出劳务人员数据');
            try {
                let { name: workerName, deptId, status: workStatus, level: workLevel } = this.form;
                let res = await remoteDownloadWorkerFile({
                    workerName,
                    deptId,
                    workStatus,
                    workLevel
                });
                let text = '劳务人员统计表';
                let fileName = '';
                if (workerName) {
                    fileName += workerName;
                }
                fileName += text;
                downloadFile(res, fileName, 'xlsx');
            } finally {
                setTimeout(hide, 100);
                this.loading = false;
            }
        },
        //下载模版
        async downloadTemplate() {
            this.loading = true;
            const hide = this.$message.loading('下载劳务人员模版');
            try {
                let res = await remoteDownloadFileTemplate();
                downloadFile(res, '劳务人员模版', 'xlsx');
            } finally {
                setTimeout(hide, 100);
                this.loading = false;
            }
        }
    }
};
</script>
<style lang="scss" scoped>
.upload_file {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    z-index: 9;
    opacity: 0;
    cursor:pointer;
}
.form_btn.search_item{
    margin-bottom:15px;
}
</style>
